package com.jvm.skill;

import org.junit.jupiter.api.Test;

/**
 * <p>
 * 当for循环中需要捕获异常信息时  尽量将try-catch移动到外部中去
 * </p>
 *
 * @author qingshan
 * @since 2020-10-11 14:11
 */
public class ForAndCatch1 {

    /**
     * 不捕获异常信息 抛出异常并结束
     */
    @Test
    public void forThrow () {
        final int size = 6;
        for (int i=0; i<size; i++){
            if(i > 3){
                throw new IllegalArgumentException(i+" is greater than 3");
            }
            System.out.println(i);
        }
    }

    /**
     * 由于内部捕获了异常，程序打印出堆栈，程序没有终止，直到正常运行结束。
     */
    @Test
    public void forThrowException(){
        final int size = 6;
        for (int i=0; i<size; i++){
            try {
                if(i > 3){
                    throw new IllegalArgumentException(i+" is greater than 3");
                }
            }catch (IllegalArgumentException e){
                e.printStackTrace();
            }
            System.out.println(i);
        }
    }

    /**
     * 由于数据运算抛出了异常，temp的值并没有改变！
     */
    @Test
    public void forExceptionEditValue(){
        final int size = 6;
        int temp = 12345;
        for (int i=0; i<size; i++){
            try {
                temp = i / 0;
                temp = 321;
            }catch (ArithmeticException e){
                e.printStackTrace();
            }
            System.out.println("i = "+i+", temp = "+temp);
        }
    }

    /**
     * 在for循环外部的程序捕获异常  当内部在一次循环中出现了异常直接抛出后 程序直接中止
     */
    @Test
    public void forOutExceptionEditValue(){
        final int size = 6;
        int temp = 12345;
        try {
            for (int i=0; i < size; i++){
                if(i > 3){
                    temp = i / 0;
                    temp = 321;
                }
                System.out.println("i = "+ i +", temp = " + temp);
            }
        }catch (ArithmeticException e){
            e.printStackTrace();
        }
    }
}
